import cv2 as cv
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication
import win32gui
import numpy as np

# 截图屏幕中微信窗口图像

hwnd_title = dict()


def get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


# 打印窗口句柄和标题
win32gui.EnumWindows(get_all_hwnd, 0)
for h, t in hwnd_title.items():
    if t is not "":
        print(h, t)


hwnd = win32gui.FindWindow(0, '梦幻西游 ONLINE - (无与伦比[本草纲目] - ″我超凶的哦[23767116])')
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()

# QImage 转cv2的mat


def qtpixmap_to_cvimg(qimg):
    temp_shape = (qimg.height(), qimg.bytesPerLine() * 8 // qimg.depth())
    temp_shape += (4,)
    ptr = qimg.bits()
    ptr.setsize(qimg.byteCount())
    result = np.array(ptr, dtype=np.uint8).reshape(temp_shape)
    result = result[..., :3]
    return result


# img = img.convertToFormat(3)
mat = qtpixmap_to_cvimg(img)

cv.imwrite("img/mh/yb_zhandou.jpg", mat)
cv.imshow("wchar", mat)
cv.waitKey(0)
cv.destroyAllWindows()
